package com.dingyh.shopwebbackground.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dingyh.shopwebbackground.entity.Orders;
import com.dingyh.shopwebbackground.entity.Payouts;
import com.dingyh.shopwebbackground.entity.ShopCar;
import com.dingyh.shopwebbackground.entity.User;
import com.dingyh.shopwebbackground.mapper.OrdersMapper;
import com.dingyh.shopwebbackground.mapper.ShopCarMapper;
import com.dingyh.shopwebbackground.service.OrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dingyh.shopwebbackground.service.UserService;
import com.dingyh.shopwebbackground.vo.LineVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dingyuhan
 * @since 2023-02-17
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    private static final String PATTERN = "MM";

    private static final String[] DATE_ARRAY = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"};


    @Autowired
    OrdersMapper ordersMapper;

    @Autowired
    ShopCarMapper shopCarMapper;

    @Autowired
    UserService userService;

    public Orders selectOrder(Map<String,Object> map){
        return ordersMapper.selectOrder(map);
    }

    public List<Orders> getOrderList(Map<String, Object> map){
        return ordersMapper.getOrderList(map);
    }

    public List<Orders> getAllList (String userId){
        return ordersMapper.getAllList(userId);
    }

    public List<Orders> getSaleList (String companyId){
        return ordersMapper.getSaleList(companyId);
    }

    public List<Orders> getOrderListTwo (){
        return ordersMapper.getOrderListTwo();
    }

    public boolean updState(Orders orders){
        try{
            return updateById(orders);
        }catch (Exception e){
            System.out.println(e);
            return false;
        }
    }

    @Override
    public boolean finishReturn(String id) {
        Orders orders = getById(id);
        orders.setState("10");
        User user = userService.getById(orders.getUserid());
        user.setMoney(user.getMoney().add(orders.getAmount()));
        User manageUser = userService.getById("3");
        manageUser.setMoney(manageUser.getMoney().subtract(orders.getAmount()));
        try{
            return updateById(orders) && userService.updateById(user) &&userService.updateById(manageUser) ;
        }catch (Exception e){
            System.out.println(e);
            return false;
        }
    }

    public boolean removeOrder(String id){
        try {
            return removeById(id);
        }catch (Exception e){
            System.out.println(e);
            return false;
        }
    }

    public Integer getOrderCount(String businessId){
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Orders::getCompanyid,businessId);
        return ordersMapper.selectCount(queryWrapper);
    }

    public Integer getNotOrderCount(String businessId){
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Orders::getState,"5");
        queryWrapper.eq(Orders::getCompanyid,businessId);
        return ordersMapper.selectCount(queryWrapper);
    }

    public List<Orders> findList(Long startTime,Long endTime, String userId) {
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getCompanyid,userId);
        queryWrapper.ge(Orders::getTimeadd,startTime)
                .le(Orders::getTimeadd,endTime);
        return list(queryWrapper);
    }

    public Map getBar(Long startTime,Long endTime, String userId) {
        List<Orders> list = findList(startTime, endTime, userId);
        if (CollectionUtils.isEmpty(list)) {
            return Collections.EMPTY_MAP;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(PATTERN);
        list.forEach(orders -> orders.setMonth(sdf.format(orders.getTimeadd()))
        );
        List<LineVO> lineVOList = new ArrayList<>();

        Map<String, List<Orders>> map = list.stream().collect(Collectors.groupingBy(Orders::getState));
        map.forEach((k, v) -> {
            BigDecimal[] array = new BigDecimal[12];
            Map<Integer, BigDecimal> moneyMap = new HashMap<>();
            v.forEach(p -> {
                String month = p.getMonth();
                BigDecimal money = Optional.ofNullable(p.getAmount()).orElse(BigDecimal.ZERO);
                BigDecimal totalMoney = Optional.ofNullable(moneyMap.get(month)).orElse(BigDecimal.ZERO);
                moneyMap.put(Integer.valueOf(month), totalMoney.add(money));
            });
            for (int i = 0; i < 12; i++) {
                array[i] = Optional.ofNullable(moneyMap.get(i)).orElse(BigDecimal.ZERO);
            }
            LineVO lineVO = LineVO.builder().name(k).moneyArray(array).build();
            lineVOList.add(lineVO);
        });
        Map<String, Object> resultMap = new HashMap<>(2);
        resultMap.put("xAxis", DATE_ARRAY);
        resultMap.put("series", lineVOList);
        return resultMap;
    }


}
